<?php
declare (strict_types=1);

namespace app\common\listener;

use app\common\model\LeaderConsumeMonth;
use app\common\model\Relation;
use app\common\model\User;

class LeaderTotal
{
    public function handle($order)
    {
        $user = User::where('id', $order->uid)->field('id,my_total,team_total,my_leader_currm,my_leader_lastm,my_leader_total,team_three_total,team_three_lastm')->find();
        $amount = $order->real_amount;

        if($order->order_type == 3){//盟主专区
            //$user->my_total += $amount;
            if(in_array($order->getData('pay_way'), ['wechat', 'alipay', 'love_bean', 'chain_bean'])){
                $user->my_leader_currm += $amount;
                $user->my_leader_total += $amount;
            }

            $month = date("Y-m");
            if($find = LeaderConsumeMonth::where(['uid'=>$user->id, 'month'=>$month])->find()){
                $find->consume_sum += $amount;
                $find->save();
            }else{
                LeaderConsumeMonth::create([
                    'uid' => $user->id,
                    'year' => date("Y"),
                    'month' => $month,
                    'consume_sum' => $amount
                ]);
            }
            $user->save();
        }

        if($parents3 = Relation::where('new_uid', $user->id)->where('algebra', '<=', 3)->column('uid')){
            User::whereIn('id', $parents3)->inc('team_three_total', floatval($amount))->update();
            User::whereIn('id', $parents3)->inc('team_three_currm', floatval($amount))->update();
        }

        /*if($parents = Relation::where('new_uid', $user->id)->column('uid')){
            User::whereIn('id', $parents)->inc('team_total', floatval($amount))->update();
        }*/

    }
}